package com.stu;

import java.util.concurrent.*;

/**
 * Created by chenhs on 2019/1/16.
 */
public class CyclicBarrierTest {
    public static void main(String[] args) throws InterruptedException {
        // 初始化barrier 对应线程的个数
        CyclicBarrier barrier = new CyclicBarrier(5);

        // 初始化线程池
        ExecutorService service = new ThreadPoolExecutor(10, 10,
                100000, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>());

        // 执行任务 todo something
        service.execute(new RunTest(0, barrier));
        service.execute(new RunTest(1, barrier));
        service.execute(new RunTest(2, barrier));
        service.execute(new RunTest(3, barrier));
        service.execute(new RunTest(4, barrier));

        // terminate executor service
        service.awaitTermination(1000, TimeUnit.SECONDS);
        service.shutdown(); // shutdown service
    }

    static class RunTest implements Runnable {
        int no; // number
        CyclicBarrier barrier;

        public RunTest(int num, CyclicBarrier barrier) {
            this.no = num;
            this.barrier = barrier;
        }

        public void run() {
            // do some work
            System.err.println("NO. " + no + " is ready for running !!!");
            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
                return;
            }
            System.err.println("NO. " + no + " running!!!!!");
        }
    }
}

